﻿namespace MetaDrive.VisualStudio.Services
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
        
    public class OutputManager
    {
        private readonly EnvDTE.DTE _dte;
        private readonly string _templatePath;
        private readonly DteProcessor _processor;

        public OutputManager(EnvDTE.DTE dte, string templatePath)
        {
            _dte = dte;
            _templatePath = templatePath;
            _processor = new DteProcessor(dte, templatePath);
        }

        public void UpdateFiles(ICollection<OutputFile> outputFiles)
        {
            foreach (var outputFile in outputFiles)
            {
                outputFile.Project = GetFullProjectPath(outputFile);
                outputFile.File = GetFullFilePath(outputFile);
            }
           
            _processor.UpdateFiles(outputFiles);
        }

        public string GetFullProjectPath(OutputInfo output)
        {
            if (string.IsNullOrEmpty(output.Project))
                return string.Empty;

            if (Path.IsPathRooted(output.Project))
                return Path.GetFullPath(output.Project);
            else
            {
                var project = GetProject(output.Project);
                if (project != null)
                    return Path.GetFullPath(project.GetFilename());
            }

            throw new Exception("Project does not exist");
        }

        public string GetFullFilePath(OutputInfo output)
        {
            // Does file contain absolute path already?
            if (Path.IsPathRooted(output.File))
            {
                return output.File;
            }

            // Resolve relative path
            string baseFile = string.IsNullOrEmpty(output.Project) ? _templatePath : output.Project;
            string baseDirectory = Path.GetDirectoryName(baseFile);
            string fullPath = Path.Combine(baseDirectory, output.File);
            return Path.GetFullPath(fullPath);            
        }

        public string GetSolutionDirectory()
        {            
            return Path.GetDirectoryName(_dte.Solution.FullName);
        }

        public EnvDTE.Project GetProject(string projectName)
        {
            return _dte.Solution.GetProjects().Where(p => p.Name == projectName).FirstOrDefault();
        }
    }
}
